// 2. 创建路由对象
// const router = express.Router()


const fs = require('fs')
const path = require('path')

const express = require('express');
const app = express();
const port = 3000;    //端口号
const request = require('request');
var bodyParser = require('body-parser')

var url = require('url');

//只要加入这个配置，在req请求对象上会多出来一个属性
//parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
//parse application/json
app.use(bodyParser.json())




// 允许跨域
app.all('*', function (req, res, next) {
  // setAllowCredentials
  res.header("Access-Control-Allow-Origin", '*');
  res.header("Access-Control-Allow-Credentials", 'true');
  res.header("Access-Control-Allow-Methods", "*");
  res.header("Access-Control-Allow-Headers", "Content-Type,Content-Length, Authorization, Accept,X-Requested-With,Authorization,DNT,Content-Type,Referer,User-Agent");
  if (req.method === "OPTIONS") res.send(200);
  else next();
});

//监听请求 *代表所有的请求路径。
//也可指定请求路径，如/text，则只能接收http://localhost:3000/text的请求
app.get('*', (req, res) => {
  //接收要转发的http地址
  var urlObj = url.parse(req.url, true);
  const { pathname, query } = urlObj
  if (pathname.indexOf('moveDetailUrl') > -1) {
    const { moveDetail } = require('./mock.js')
    res.send({ code: 200,   moveDetail  });
    return
  } else if (pathname.indexOf('bookDetailUrl') > -1) {
    const { bookDetail } = require('./mock.js')
    res.send({ code: 200,  bookDetail });
    return
  }
  const options = {
    url: pathname.replace('/', ''),
    method: "GET",
    qs: query,
    //headers: req.headers    //如果需要设置请求头，就加上
  }
  request(options, function (error, response, body) {
    if (!error && response.statusCode === 200) {
      //拿到实际请求返回的响应头，根据具体需求来设置给原来的响应头
      let headers = response.headers;
      res.setHeader('content-type', headers['content-type']);
      res.send({ code: 200, body });
    } else {
      res.send({ code: 200, options });
    }
  });
})

app.post('*', (req, res) => {
  let userListJson = path.join(__dirname, 'userList.json')
  var urlObj = url.parse(req.url, true);
  const { pathname, query } = urlObj
  const { username, password } = req.body

  // 登陆 ------------------------------------------
  if (pathname.indexOf('loginPost') > -1) {
    let datat = fs.readFileSync(userListJson, 'utf-8')

    const list = JSON.parse(datat).data.list
    const hasUserName = list.some((e) => e.username === username && e.password === password);
    if (hasUserName) {
      const { id } = list.find((e) => e.username === username && e.password === password);
      res.send({ code: 200, msg: '登录成功', data: { username, id } })
    } else {
      res.send({ code: -200, msg: '账号/密码错误', data: {} })
    }
    return
  }

  // 注册 ------------------------------------------
  if (pathname.indexOf('registerPost') > -1) {
    const options = {
      url,
      method: 'POST',
      json: req.body,    //content-type是application/json的时候使用,其它请查看requiest用法
      headers: {
        token: req.headers.token,
        'content-type': req.headers['content-type']
      }
    }


    //将地址赋值给
    //读取当前data.json文件内容 同步
    let datat = fs.readFileSync(userListJson, 'utf-8')
    //定义一个数组存放读取到的数据
    let datatParse = JSON.parse(datat)
    let arr = datatParse.data.list
    //将新记录添加到数组中
    if (!(arr.every((_) => _.username !== req.body.username))) {
      res.send({ code: -200, msg: '账户名重复', list: [] })
      return
    }

    arr.push({ username, password, id: arr.length +1 });
    //添加后写入b.json文件
    fs.writeFile(userListJson, JSON.stringify(datatParse), 'utf-8', function (err) {
      if (err) {
        res.send({ code: -200, msg: '服务器异常', data: {} })
        throw err;
        return
      }
      res.send({ code: 200, msg: '注册成功', data: { username, id }})
    })

  }
})

app.listen(port, () => {
})



var PORT = 3000;


